// mircoApp/tx-team-performance/apply/apply.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    plugin_name: '',
      objValue: {},
      showPicker: false,

      addressShow: false,
      streetShow: false,
      districtVal: [],

      fileList: [],

      columns: [],
      formList: [{
        name: 'level_id',
        label: '申请等级',
        readonly: true,
        placeholder: '请输入身份等级',
        rules: [{
          required: true
        }]
      },{
        name: 'corporate_name',
        label: '公司名称',
        placeholder: '请输入公司名称',
        rules: [{
          required: true
        }],
      },{
        name: 'enterprise_code',
        label: '企业代码',
        placeholder: '请输入企业代码',
        rules: [{
          required: true
        }],
      },{
        name: 'juridical_person',
        label: '法人代表',
        placeholder: '请输入法人代表',
        rules: [{
          required: true
        }],
      },{
        name: 'contacts',
        label: '联系人',
        placeholder: '请输入联系人',
        rules: [{
          required: true
        }],
      },{
        name: 'mobile',
        label: '联系电话',
        placeholder: '请输入联系电话',
        rules: [{
          required: true
        }],
      },{
        name: 'account',
        label: '对公账户',
        placeholder: '请输入对公账户',
        rules: [{
          required: true
        }],
      },{
        name: 'bank',
        label: '开户行',
        placeholder: '请输入开户行',
        rules: [{
          required: true
        }],
      },{
        name: 'area',
        label: '开户地址',
        placeholder: '请输入开户地址',
        readonly: true,
        rules: [{
          required: true
        }]
      },{
        name: 'address',
        label: '详情地址',
        placeholder: '请输入详情地址',
        rules: [{
          required: true
        }],
        click: () => {}
      },{
        uploader: true,
        name: 'business_license',
        label: '营业执照',
        placeholder: '请上传营业执照',
        rules: [{
          required: true,
          message: '请上传营业执照'
        }],
        class: 'input-class-diy'
      }],

      pickerValue: [0, 0, 0],
      provinceData: [],
      cityData: [],
      districtData: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },
  getData(){
    let urlStr = app.getNetAddresss("plugin.tx-team-performance.frontend.controllers.member.index");
    app._getNetWork({
      url: urlStr,
      success: (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          wx.setNavigationBarTitle({
            title: res.data.plugin_name
          });
          if(res.data.need_sign) {
            wx.showModal({
              title: '您尚未签订协议',
              content: `需要签订协议后，才可进行填写${res.data.plugin_name}身份等级申请信息`,
              confirmText: '去签署',
              success (ress) {
                if (ress.confirm) {
                  wx.navigateTo({
                    url: '/packageH/sign_shopV2/index/index?scene=5',
                  });
                } else if (ress.cancel) {
                  wx.navigateBack({
                    delta: 1
                  })
                }
              }
            });
            return;
          }
          if(res.data.wait) {
            return wx.showModal({
              title: '等待审核',
              content: `您的身份申请正在审核中，请耐心等待审核`,
              confirmText: '返回',
              showCancel: false,
              success (ress) {
                wx.navigateBack({
                  delta: 1
                })
              }
            });
          }
          this.setData({
            columns: res.data.levels
          });
          //加载地址数据初始化
          this._initAddressInfo();
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  onSubmit(){
    let info = {};
    const emptyModel = this.data.formList.find((model) => {
      return model.model === ''||!model.model;
    });
    if (emptyModel) {
      return wx.showToast({
        icon: 'none',
        title: `请填写${emptyModel.label}`,
        duration: 1500
      });
    }
    this.data.formList.forEach(key =>
      info[key.name] = key.model
    );
    let json = {...info,...this.data.objValue};
    app._postNetWork({
      url: app.getNetAddresss("plugin.tx-team-performance.frontend.controllers.member.apply"),
      data: json,
      success: (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          wx.reLaunch({
            url: '/packageG/member_v2/member_v2'
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  onChangeField(e) {
    this.setData({
      ['formList[' + this.activeClickIndex + '].model']: e.detail,
    });
  },
  onClickField(e) {
    let { index, name } = e.currentTarget.dataset;
    this.activeClickName = name;
    this.activeClickIndex = index;
    if(name == 'level_id'){
      this.setData({
        showPicker: true
      });
    } else if(name == 'area'){
      this.setData({
        addressShow: true
      });
    }
  },
  onConfirm(e){
    this.setData({
      ['formList[' + this.activeClickIndex + '].model']: e.detail.value.name,
      showPicker: false
    });
    this.data.objValue[this.activeClickName] = e.detail.value.id;
  },
  onCancel(){
    this.setData({
      showPicker: false
    })
  },

  // 关闭选择收货地址
  _closeDateLw: function () {
    this.setData({
      addressShow: false,
    });
  },
  //地址选择器数据初始化
  _initAddressInfo: function () {
    var that = this;
    var _keyName = "provinceData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("地址信息准备就绪");
        that._getProvinceData();
      },
      fail: function (res) {
        console.log("省fail");
        app._getNetWork({
          url: app.getNetAddresss("member.member-address.address"),
          success: function (res) {
            var response = res.data;
            var province = response.data.province;
            var city = response.data.city;
            var district = response.data.district;
            wx.setStorage({
              key: "provinceData",
              data: province,
            });
            wx.setStorage({
              key: "cityData",
              data: city,
            });
            wx.setStorage({
              key: "districtData",
              data: district,
            });
            that._initAddressInfo();
          },
          fail: function (res) {},
          state: true,
        });
      },
    });
  },
  // 读取省key
  _getProvinceData: function () {
    var that = this;
    var _keyName = "provinceData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        that.setData({
          provinceData: res.data,
        });
        that.setData({
          "selectAddressData[0].name":
            res.data[that.data.pickerValue[0]].areaname,
          "selectAddressData[0].id": res.data[that.data.pickerValue[0]].id,
          "selectAddressData[0].index": that.data.pickerValue[0],
        });
        that._getCityData();
      },
    });
  },
  // 读取城市key，筛选城市data
  _getCityData: function () {
    var _data = this.data.selectAddressData[0];
    var that = this;
    var _keyName = "cityData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        that.setData({
          cityData: _json,
        });
        that.setData({
          "selectAddressData[1].name": _json[that.data.pickerValue[1]].areaname,
          "selectAddressData[1].id": _json[that.data.pickerValue[1]].id,
          "selectAddressData[1].index": that.data.pickerValue[1],
        });
        that._getDistrictData();
      },
    });
  },
  // 读取地区key，筛选地区data
  _getDistrictData: function () {
    var _data = this.data.selectAddressData[1];
    var that = this;
    var _keyName = "districtData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        that.setData({
          districtData: _json,
        });
        that.setData({
          "selectAddressData[2].name": _json[that.data.pickerValue[2]].areaname,
          "selectAddressData[2].id": _json[that.data.pickerValue[2]].id,
          "selectAddressData[2].index": that.data.pickerValue[2],
        });
      },
    });
  },
  // 收货地址滚动事件
  bindChange: function (e) {
    var val = e.detail.value;
    if (this.data.pickerValue[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
    }
    if (this.data.pickerValue[1] != val[1]) {
      val[2] = 0;
    }
    this.setData({
      "pickerValue[0]": val[0],
      "pickerValue[1]": val[1],
      "pickerValue[2]": val[2],
    });
    this._initAddressInfo();
  },
  //城市结果
  resultAdd: function () {
    let seleData = this.data.selectAddressData;
    let retCity = seleData[0].name + " " + seleData[1].name + " " + seleData[2].name;
    this.setData({
      ['formList[' + this.activeClickIndex + '].model']: retCity,
      addressShow: false,
    });
    this.data.objValue.province_id = seleData[0].id;
    this.data.objValue.city_id = seleData[1].id;
    this.data.objValue.district_id = seleData[2].id;

    this.getStreet(seleData[2].id);
  },
  //获取街道
  getStreet(param) {
    let urlStr = app.getNetAddresss("member.memberAddress.street");
    urlStr += "&district_id=" + param;
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          if (!app._isTextEmpty(res.data) && res.data.length > 0) {
            this.setData({
              districtVal: res.data,
              streetShow: true,
            });
          }
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  streetConfirm(e) {
    let item = e.currentTarget.dataset.item;
    this.setData({
      ['formList[' + this.activeClickIndex + '].model']: this.data.formList[this.activeClickIndex].model + " " + item.areaname,
      streetShow: false,
    });
    this.data.objValue.street_id = item.id;
  },

  onRead(event) {
    const { file } = event.detail;
    let urlStr = app.getNetAddresss('upload.uploadPic');
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: urlStr,
      filePath: file.url,
      name: 'file',
      success:(resdata)=> {
        let res = JSON.parse(resdata.data);
        if (res.result == 1) {
          this.data.objValue[this.activeClickName] = res.data.img;
          // 上传完成需要更新 fileList
          const { fileList = [] } = this.data;
          fileList.push({ ...file, url: res.data.img_url });
          this.setData({ 
            fileList,
            ['formList[' + this.activeClickIndex + '].model']: res.data.img
           });
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1500,
          });
        }
      },
    });
  },
  delImg(){
    this.setData({ fileList: [] });
    this.data.objValue[this.activeClickName] = '';
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})